package com.link.linkupjavaweb.controller.admin;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.dto.AdminLoginDTO;
import com.link.linkupjavaweb.entity.Admin;
import com.link.linkupjavaweb.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 管理员认证Controller
 */
@Controller
@RequestMapping("/admin")
public class AdminAuthController {
    
    @Autowired
    private AdminService adminService;
    
    /**
     * 跳转到管理员登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "admin/login";
    }
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    @ResponseBody
    public Result<Admin> login(@RequestBody AdminLoginDTO loginDTO, HttpSession session) {
        try {
            Admin admin = adminService.login(loginDTO);
            // 将管理员信息存入Session
            session.setAttribute(Constants.SESSION_ADMIN, admin);
            return Result.success("登录成功", admin);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 管理员退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 清除Session
        session.removeAttribute(Constants.SESSION_ADMIN);
        session.invalidate();
        return "redirect:/admin/login";
    }
    
    /**
     * 获取当前登录管理员信息
     */
    @GetMapping("/current")
    @ResponseBody
    public Result<Admin> getCurrentAdmin(HttpSession session) {
        Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
        if (admin == null) {
            return Result.error("未登录");
        }
        return Result.success(admin);
    }
}

